<template>
   <div class="app-container">
      <div class="map-all app-left app-left-width bg-white app-height">
         <!--全局地图-->
            <div class="head-container-tit">
               <span class="map-icon"></span> 全局地图目录
            </div>
            <div class="head-container">
               <el-input
                  v-model="dirName"
                  placeholder="数据库名、表名进行查询"
                  clearable
                  size="small"
                  suffix-icon="el-icon-search"
                  @input="handleDirName"
                  style="margin-bottom: 20px"
               >
                  <el-select v-model="libraryOrtable" slot="prepend" @change="selectHandleLibrary" placeholder="请选择" class="input-with-select">
                     <el-option label="按库名" value="library"></el-option>
                     <el-option label="按表名" value="tableNme"></el-option>
                     <el-option label="按字段名" value="fieldName"></el-option>
                  </el-select>
               </el-input>
            </div>
            <div class="mytree">
               <div style="overflow:auto;display:-webkit-inline-box">
                  <el-tree
                     v-show="libraryOrtable == 'library' || libraryOrtable == '按库名'"
                     :data="databaseTree"
                     :props="defaultProps"
                     :expand-on-click-node="false"
                     :filter-node-method="filterNode"
                     :highlight-current='true'
                     ref="tree"
                     node-key="id"
                     :indent='0'
                     :current-node-key="currentNodeKey"
                     default-expand-all
                     @node-click="handleNodeClick"
                  >
                  </el-tree>
               </div>
               <div v-show="libraryOrtable == 'tableNme' || libraryOrtable == 'fieldName' ">
                  <div v-show="!tableList.length" class="not-data">暂无数据</div>
                  <div class="table-item" v-for="(item,index) in tableList" :key="index"  @click="handlebtableNodeClick(item)">
                     <div :class="['table-item-top',item.tableName.length>30?'narrowSize':'']">{{item.tableName}}</div>
                     <div class="table-item-bottom">{{item.tableAlias}}</div>
                  </div>
               </div>
            </div>
      </div>   
         <!--用户数据-->
         <!---<el-col :span="19" :xs="24"  class="map-container" :style='{height:containerHeight+"px"}'>-->
      <div class="app-right bg-white app-height">
         <el-row :gutter="20" type="flex">
            <el-col :span="24" class="map-container">
               <div class="search-item">
                  <el-form
                     :model="queryParams"
                     ref="queryForm"
                     :inline="true"
                     v-show="showSearch"
                     label-width="108"
                  >
                     <el-form-item label="表名称：" prop="tableName">
                        <el-input
                           v-model="queryParams.tableName"
                           placeholder="请输入表名称"
                           size="small"
                           style="width: 240px"
                        />
                     </el-form-item>
                     <el-form-item label="字段名称：" prop="fieldName">
                        <el-input
                           v-model="queryParams.fieldName"
                           placeholder="请输入字段名称"
                           size="small"
                           style="width: 240px"
                        />
                        <!--@keyup.enter.native="handleQuery"-->
                     </el-form-item>
                     <el-form-item label="我的权限：" prop="accessType">
                        <el-select
                           v-model="queryParams.accessType"
                           placeholder="请选择权限"
                           clearable
                           size="small"
                           style="width: 240px"
                        >
                           <el-option value="1" label="只读"></el-option>
                           <el-option value="2" label="可读可导出"></el-option>
                           <el-option value="3" label="内容编辑"></el-option>
                           <el-option value="4" label="元数据编辑"></el-option>
                           <el-option value="5" label="管理权限"></el-option>
                        </el-select>

                     </el-form-item>
                  </el-form>
                  <el-row :gutter="10" class="operation">
                     <div class="view-select float-left">
                        <span>视图模式：</span>
                        <el-checkbox-group
                           v-model="checked"
                           @change="handleCheckedCitiesChange"
                           class="view-select-checkbox"
                        >
                           <el-checkbox label="1">列表模式</el-checkbox
                           ><el-checkbox label="2">地图模式</el-checkbox>
                        </el-checkbox-group>
                     </div>
                     <div class="float-right">
                        <el-col :span="1.5">
                           <el-button plain
                              type="primary"
                              icon="el-icon-search"
                              size="mini"
                              @click="handleAdd"
                              >查询</el-button
                           >
                        </el-col>
                        <el-col :span="1.5">
                           <el-button  plain
                              type="primary"
                              icon="el-icon-refresh-right"
                              size="mini"
                              @click="handleUpdate">刷新</el-button>
                        </el-col>
                        <el-col :span="1.5">
                           <el-button  plain
                              type="primary"
                              icon="el-icon-tickets"
                              size="mini"
                              @click="handleApplyPermis"
                              >申请
                           </el-button>
                        </el-col>
                        <el-col :span="1.5">
                           <el-select
                              value=''
                              placeholder="更多操作"
                              class="select-more-handle"
                              @change="selectMore">
                              <el-option
                                 class="select-more-option"
                                 v-for="item in options"
                                 :key="item.value"
                                 :label="item.label"
                                 :value="item.value">
                                 <div class="select-more-option-item">
                                    <span style="display:inline-block;padding-right:5px;"><i :class="item.icon"></i></span>
                                    <span style="display:inline-block; color: #8492a6; font-size: 13px">{{ item.label }}</span>
                                 </div>
                              </el-option>
                           </el-select>
                        </el-col>
                     </div>
                  </el-row>
               </div>

               <el-table
                  v-loading="loading"
                  :data="databaseList"
                  border
                  :max-height=mapHeight
                  v-show="checked[0] == 1"
                  @selection-change="handleSelectionChange"
               >
                  <el-table-column type="selection" width="50" align="left"  sortable/>
                  <el-table-column label="表单名称" align="left"  key="tableAlias"  prop="tableAlias" sortable>
                  	<template slot-scope="scope">
                        <a href="javascript:;" style="color:#409eff;" @click="handleGoto(scope.row)">{{scope.row.tableAlias}}</a>
                     </template>
                  </el-table-column>
                  <el-table-column label="表单名称（数据库）" align="left" key="tableName" prop="tableName" sortable :show-overflow-tooltip="true"/>
                  <el-table-column  label="安全等级" align="center" key="safeLevel" prop="safeLevel"  sortable width="120" :show-overflow-tooltip="true" />
                  <el-table-column label="表单简介"  align="left"  key="comment"  prop="comment"  sortable :show-overflow-tooltip="true"  />
                  <el-table-column  label="我的权限" align="center"  key="accessType"  prop="accessType"  sortable width="120">
                  </el-table-column>
               </el-table>
               <!--数据地图-->
               <div v-show="checked[0] == 2" class="mapModel">
                  <TreeItem :mapHeight="mapHeight" :treeData="propsMap" ref="mapSelect"></TreeItem>
               </div>
               <pagination
                  v-show="total > 0 && checked==1"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList"
               />
            </el-col>
         </el-row>
      </div>
      <!--权限申请---->
	<el-dialog
      title="权限申请"
      :visible.sync="dialogVisiblePermis"
      :destroy-on-close="true"
      width="75%"
      :before-close="handlePermisClose">
      <MapPermis @clonePermis="handlePermisClose"/>
   </el-dialog>
   </div>
</template>
<style>
</style>
<style lang="scss" scoped>
  @import "~@/assets/styles/system/tree.scss";
/**
    Element class start
  **/
  ::v-deep.el-tree--highlight-current {
     width:100%
  }
.head-container ::v-deep{
   .el-select .el-input {
    width: 100px;
  }
   .el-input__inner{
      padding-right:44px;
   }
   .el-input__suffix-inner{
      display: inline-block;
      .el-icon-search{
         display: inline-block;
         width:44px;
         font-size:16px;
      }
   }
   >.el-input__suffix::before{
      content: '';
      display: inline-block;
      border-left:1px solid #ddd;
      height:20px;
      position: absolute;
      top:50%;
      margin-top:-10px;
      left:0;
   }
   .el-input-group__prepend {
      background-color: #fff;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      .el-input__inner{
         height: 32px;
         line-height: 31px;
      }
   }
}
.el-row {
   margin-right: 0px !important;
   margin-left: 0px !important;
}
.el-checkbox__input.is-checked + .el-checkbox__label {
   padding-right: 6px !important;
}
/**
    Element class end
  **/
.app-container::v-deep{
   padding:0;
   background: #F4F4F4;
   .el-checkbox__label, .el-button--mini, .el-form-item__label{
      font-size:14px;
   }
}
.head-container-tit {
   display: flex;
   align-items: center;
   font-size: 18px;
   padding:5px 0 20px 0;
   .map-icon {
      width: 4px;
      height: 21px;
      display: inline-block;
      background: #1183f8;
      margin-right: 8px;
   }
}
.table-item{
   border-bottom:1px solid #ddd;
    color:#606266;
   &:hover{
      cursor: pointer;
      background-color: #F5F7FA;
   }
   .table-item-top{
      font-size: 16px;
      font-weight: bold;
      padding-left:10px;
      margin-top:10px;
   }
   .narrowSize{
      font-size:14px;
   }
   .table-item-bottom{
      padding:10px 0;
      font-size: 12px;
      padding-left:10px;
   }
}
.not-data{
   font-size:14px;
   color:#909399;
   text-align: center;
   line-height:60px;
}
.mytree{
   height:673px;
   overflow: auto;
}
.operation {
   font-size:14px;
   padding-bottom: 10px;
   .view-select {
      line-height: 34px;
      color:#606266;
      .view-select-checkbox {
         display: inline-block;
      }
      label {
         margin-right: 20px;
      }
   }
   .el-button--mini {
      height: 32px;
   }
   .select-more-handle {
      width: 106px;
   }
}

.select-more-option {
   &:first-child .select-more-option-item {
      border-top: none;
   }
   .select-more-option-item {
      border-top: 1px solid #e6e6e6;
      text-align: center;
   }
}

.map-container {
   padding: 30px 20px!important;
}
</style>
<script>
import TreeItem from "../TreeItem";
import MapPermis from "./mapPermis";
import {mapTreeItem} from "@/api/dataManagement/system/dir";
import {getDatabeseList,getTableMapList,searchTableList,searchFieldsList} from "@/api/dataManagement/system/info";
import {setTypeListSelect,getHeight} from "@/utils/zkComm";
export default {
   name: "User",
   components: {TreeItem ,MapPermis},
   data() {
      return {
         // 遮罩层
         loading: false,
         // 选中数组
         ids: [],
         // 非单个禁用
         single: true,
         // 非多个禁用
         multiple: true,
         // 显示搜索条件
         showSearch: true,
         // 总条数
         total: 0,
         // 末节点表格数据
         databaseList:[],
         // 部门树选项
         databaseTree: undefined,
         // 数据库表名称
         dirName: undefined,
         // 表单参数
         form: {},
         defaultProps: {
            children: "children",
            label: "dirName"
         },
         currentNodeKey:undefined,
         // 查询参数
         queryParams: {
            pageNum: 1,
            pageSize: 30,
            tableName: undefined,
            fieldName: undefined,
            accessType: undefined,
            dirId: 0
         },
         // 视图模式
         viewModelOptions: [
            { dictLabel: "列表模式", dictValue: 1 },
            { dictLabel: "地图模式", dictValue: 2 }
         ],
         mapHeight: undefined,
         containerHeight: 0,
         checked: ["1"],
         morehandleValue: "",
         options: [
            {
               value: "newCreate",
               label: "新建",
               icon: "el-icon-plus"
            },
            {
               value: "copyValue",
               label: "复制",
               icon: "el-icon-document-copy"
            },
            // {
            //    value: "deleteValue",
            //    label: "删除",
            //    icon: "el-icon-delete"
            // }
         ],
         selectionList:[],
         propsMap:[],
         libraryOrtable:'按库名',
         tableList:[],
         dialogVisiblePermis:false
      };
   },
   watch: {
      // 根据名称筛选部门树
      dirName(val) {
         if(this.libraryOrtable == '按库名' || this.libraryOrtable == 'library') {
            if(!val) return this.getDatabaseTree();
            this.$refs.tree.filter(val.toUpperCase());
            // }
         }
      },
      currentNodeKey(id) {
      // Tree 内部使用了 Node 类型的对象来包装用户传入的数据，用来保存目前节点的状态。可以用 $refs 获取 Tree 实例
         var that =  this;
         if (id.toString()) {
            var that =  this;
            that.$nextTick(()=>{
               that.$refs.tree.setCurrentKey(Number(id));
            })
         } else {
            that.$nextTick(()=>{
               that.$refs.tree.setCurrentKey(Number(id));
            })
         }
      }
   },
   created() {
      this.getDatabaseTree()
      // 通过路由进行监听dirId  来获取仓库的表
      // this.queryParams.dirId = this.$route.params.dirId
      // this.getTableMapList();
      // console.log(all,'all')
      this.currentNodeKey = Number(this.$route.query.dirId)
   },
   mounted() {
      this.mapHeight = getHeight(true,this.databaseList.length)+10
   },
   methods: {
      handleApplyPermis(){
         if(this.checked[0] == 2){
            this.$refs.mapSelect.selectMap('申请')
         } else {
            if(this.selectionList.length == 0){
            this.$message({
                     message: '请选择数据列表中的数据才能进行权限申请',
                     type: 'error'
               })
               return false;
            }
            sessionStorage.setItem("selectList",JSON.stringify(this.selectionList))

             this.dialogVisiblePermis =  true
            // this.$router.push("/DMS/dataMap/mapDirectory/mapPermis?dirId="+this.selectionList[0].dirId);
         }
      },
      // // 获取数据库表单目录
      getDatabaseTree(){
         mapTreeItem().then(res=>{
            if(res.code==200){
               this.databaseTree = res.data.children
               this.queryParams.dirId =  this.$route.query.dirId || this.databaseTree[0].children[0].id
               sessionStorage.setItem("dirId",JSON.stringify(this.databaseTree[0].children[0].id))
               this.getList();
            }
         })
      },
      // 获取地图模式
      getTableMapList(){
         getTableMapList({...this.queryParams}).then(res=>{
            this.propsMap = res.data;
         })
      },
      // 监听地图搜索框
      handleDirName(){
         if(this.libraryOrtable =='tableNme' || this.libraryOrtable =='fieldName'){
            if(!this.dirName){
               this.tableList =[]
            }
            if((this.libraryOrtable =='tableNme' && this.dirName.length > 2) || this.libraryOrtable =='fieldName'){
               let url = ''
               let queryParasm = {}
               if(this.libraryOrtable =='tableNme' ){
                  url = searchTableList
                  queryParasm = { tableName:this.dirName }
               } else {
                  url = searchFieldsList
                  queryParasm = { fieldName:this.dirName }
               }
               // searchTableList({tableName:this.dirName}).then(res=>{
               url(queryParasm).then(res=>{
                  var data= res.data;
                  
                  for(var i=0;i<data.length;i++){
                     data[i].children = []
                     data[i].tableNameAndabAlias = data[i].tableName + ' | ' +data[i].tableAlias
                  }
                  this.tableList = data
               })
            }
         }
      },
      // 监听地图下拉框
      selectHandleLibrary(){
         this.dirName =''
         if(this.libraryOrtable =='tableNme' || this.libraryOrtable =='fieldName') {
             this.tableList = [];
         } else {
            this.getDatabaseTree();
            this.defaultProps.label = 'dirName';
         }
      },
      //查询按钮
      handleAdd(){
         if(this.checked[0] == 1){
            this.getList()
         } else {
            this.getTableMapList()
         }
      },
      // 刷新按钮
      handleUpdate(){
         this.queryParams={
            pageNum: 1,
            pageSize: 30,
            tableName: undefined,
            fieldName: undefined,
            accessType: undefined,
            dirId: this.$route.query.dirId
         };
         if(this.checked[0] == 1){
            this.getList()
         } else {
            this.$refs.mapSelect.selectMap('更新')
            this.getTableMapList()
         }
      },
      /** 查询用户列表 */
      getList() {
         this.loading = true;
         var dirId =  this.$route.query.dirId
         if(this.queryParams.dirId == 0 && dirId) this.queryParams.dirId = dirId;
         if(!dirId){
            this.loading = false;
            return false;
         }
         getDatabeseList({...this.queryParams}).then(res=>{
            if(res.code == 200 && res.rows){
               var data = res.rows
               for(var i=0;i<data.length;i++){
                  data[i].accessType = setTypeListSelect(data[i].accessType,'')
               }
               this.databaseList =  data;
               this.total =  res.total;
               this.loading = false;
            }
         })
      },
      // 筛选节点
      filterNode(value, data,node) {
         // if (!value) return true;
         // if(this.libraryOrtable == '按库名'){
         //    console.log(data)
         //    return data.dirName.indexOf(value) !== -1;
         // } else {
         //    console.log(data)
         // }
           if (!value) return true;
            let _array = []; //这里使用数组存储 只是为了存储值。.

            this.getReturnNode(node, _array, value);
            let result = false;
            _array.forEach(item => {
               result = result || item;
            });
            return result;
      },
      getReturnNode(node, _array, value){
         let isPass =
         node.data &&
         node.data.dirName &&
         node.data.dirName.indexOf(value) !== -1;
         isPass ? _array.push(isPass) : "";
         if (!isPass && node.level != 1 && node.parent) {
            this.getReturnNode(node.parent, _array, value);
         }
      },
      // 节点单击事件
      handleNodeClick(data) {
         if(this.libraryOrtable == 'library' || this.libraryOrtable == '按库名') {
            if(this.$route.query.dirId == data.id) return;
            this.queryParams.dirId = data.id;
            this.queryParams = Object.assign(this.queryParams,{ tableName: undefined,fieldName: undefined,accessType: undefined,})
            this.$router.push("/DMS/dataMap/mapDirectory?dirId="+data.id);
            this.getList();
            this.getTableMapList()
         }
      },
      handlebtableNodeClick(data){
           this.$router.push("/DMS/dataMap/mapDirectory/details/"+data.id+'?dirId='+data.dirId);
      },
		// select 选择更多 按钮
		selectMore(value){
            if(value == "newCreate"){
               this.$router.push("/DMS/dataMap/mapDirectory/mapCreate");
            }
            if(value == "copyValue"){
               if(this.checked[0] == 2){
                  this.$refs.mapSelect.selectMap('复制')
               }else {
                  if(!this.selectionList.length) {
                     this.$message({
                        message: '请选择数据列表中的数据才能进行复制',
                        type: 'error'
                     })
                     return false;
                  }
                  sessionStorage.setItem("selectList",JSON.stringify(this.selectionList))
                  this.$router.push("/DMS/dataMap/mapDirectory/mapCopy?dirId="+this.$route.query.dirId);
                }
            }
            if(value == "deleteValue"){
               this.$router.push("/DMS/dataMap/mapDirectory/mapDelete");
            }
		},
      //  视图模式切换
      handleCheckedCitiesChange(value, index) {
         if (this.checked.length) {
            this.checked = [];
            this.checked = [value[1] + ""];
            if(this.checked[0] == 1) {
               this.getList()
               this.mapHeight = getHeight(true)+40
            } else {
               this.getTableMapList()
               this.mapHeight = getHeight(false)+40
            }
         } else {
            this.checked.push("1");
         }
      },

      // 表单重置
      reset() {
         this.form = {
            userId: undefined,
            deptId: undefined,
            userName: undefined,
            nickName: undefined,
            password: undefined,
            phonenumber: undefined,
            email: undefined,
            sex: undefined,
            status: "0",
            remark: undefined,
            postIds: [],
            roleIds: []
         };
         this.resetForm("form");
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
         this.selectionList =  selection
         this.ids = selection.map(item => item.userId);
         this.single = selection.length != 1;
         this.multiple = !selection.length;
      },
      handleGoto(row){
         this.$router.push("/DMS/dataMap/mapDirectory/details/"+row.id+'?dirId='+this.queryParams.dirId);
      },
      handlePermisClose(){
         this.dialogVisiblePermis =  false
         this.getList();
      }
   }
};
</script>
